package com.atjava.nebula.weixin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Date;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.atjava.nebula.web.action.BaseViewAction;
import com.atjava.nebula.weixin.sdk.WXBizMsgCrypt;

@Controller
@RequestMapping("/weixin")
public class WeixinRecallAction extends BaseViewAction {

	@RequestMapping(value="/weixin/recall" ,method = RequestMethod.POST)
	public String weixinService(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		String sToken = "QDG6eK";
		String sCorpID = "wx5823bf96d3bd56c7";
		String sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";

		WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
		
		//微信加密签名
        String signature = request.getParameter("msg_signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        String echostr = request.getParameter("echostr");
        
        
    	String sEchoStr; //需要返回的明文
		
		
		
        if(echostr != null && !echostr.isEmpty()){
        	try {
    			sEchoStr = wxcpt.VerifyURL(signature, timestamp,nonce, echostr);
    			System.out.println("verifyurl echostr: " + sEchoStr);
    			// 验证URL成功，将sEchoStr返回
    			 response.getWriter().write(echostr);
            	 response.getWriter().flush();  
    		} catch (Exception e) {
    			//验证URL失败，错误原因请查看异常
    			e.printStackTrace();
    		}
        }else{
            String postData = readStreamParameter(request.getInputStream()) ;
            try {
    			String sMsg = wxcpt.DecryptMsg(signature, timestamp, nonce, postData);
    			System.out.println("after decrypt msg: " + sMsg);
    			// TODO: 解析出明文xml标签的内容进行处理
    			// For example:
    			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    			DocumentBuilder db = dbf.newDocumentBuilder();
    			StringReader sr = new StringReader(sMsg);
    			InputSource is = new InputSource(sr);
    			Document document = db.parse(is);

    			Element root = document.getDocumentElement();
    			NodeList nodelist1 = root.getElementsByTagName("Content");
    			String Content = nodelist1.item(0).getTextContent();
    			System.out.println("Content：" + Content);
    			
    		} catch (Exception e) {
    			// TODO
    			// 解密失败，失败原因请查看异常
    			e.printStackTrace();
    		}
       }
        
        String sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>";
    	try{
    		String sEncryptMsg = wxcpt.EncryptMsg(sRespData, String.valueOf(new Date().getTime()), nonce);
    		System.out.println("after encrypt sEncrytMsg: " + sEncryptMsg);
    		// 加密成功
    		// TODO:
    		// HttpUtils.SetResponse(sEncryptMsg);
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    		// 加密失败
    	}
  

   return null;
	
}
	
	
	  //从输入流读取post参数  
    public String readStreamParameter(ServletInputStream in){  
        StringBuilder buffer = new StringBuilder();  
        BufferedReader reader=null;  
        try{  
            reader = new BufferedReader(new InputStreamReader(in));  
            String line=null;  
            while((line = reader.readLine())!=null){  
                buffer.append(line);  
            }  
        }catch(Exception e){  
            e.printStackTrace();  
        }finally{  
            if(null!=reader){  
                try {  
                    reader.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return buffer.toString();  
    } 

}
